﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace RestUpMVC.Representation
{
    /// <summary>
    /// An XML representation of a resource.
    /// </summary>
    public class XmlRepresentation : IRepresentation
    {
        private object _resource;

        public virtual string ContentType
        {
            get { return "application/xml"; }
        }

        public virtual void SetResource(object resource)
        {
            if (resource == null) throw new ArgumentNullException("resource");
            _resource = resource;
        }

        /// <summary>
        /// Converts the resource into an XML representation.
        /// </summary>
        /// <exception cref="ArgumentNullException">Thrown if the resource argument is null.</exception>
        /// <returns></returns>
        public virtual string ConvertResource()
        {
            var stringWriter = new StringWriter();
            var xmlSerializer = new XmlSerializer(_resource.GetType());
            xmlSerializer.Serialize(stringWriter, _resource);
            return stringWriter.ToString();
        }
    }
}